<?php
// +----------------------------------------------------------------------
// | Author: 发仔 <i@fazi.me> 
// +----------------------------------------------------------------------

namespace app\admin\controller;

use think\Db;

class role extends Base
{
	
	protected $beforeActionList = ['tree'];
	
    public function index() {

		return $this->out();
		
	}
	
	public function add() {
		
		if(request()->isPost()) {
			
			$data = $this->data();
			$rslt = Db::name('role')->insert($data);
			
			return $this->res($rslt,'添加成功','role/index');
		}
		//选项 
		$this->allot();
		
		return $this->out();
		
	}
	
	public function edit() {
		
		$id = input('param.role_id/d');
		
		if(!$id) {
			return $this->error('入口非法，请重试');
		}
		//提交
		if(request()->isPost()) {
			
			$data = $this->data();
			$rslt = Db::name('role')->where('role_id',$id)->update($data);
			
			return $this->res($rslt,'','role/index');
			
		}
		
		$item = Db::name('menu')->find($id);
		//选项
		$this->assign('item',$item);
		$this->assign('area', TplOptions($this->tree,$item['pid'],'name','id'));
		
		return $this->out('add');
		
	}
	
	protected function data() {
		$P = input('post.');
				
		$data = [
			'name' => trim($P['name']),
			'area_id' => intval($P['area_id']),
		];
		
		return $data;
	}
	
	//分配菜单、权限
	protected function allot() {
		
		$ztree = Db::name('menu')->field('id,name,pid AS pId')->select();
		$ztree[0]['open'] = true;
//		halt($ztree);
		$this->assign('zTree',json_encode($ztree));
		
	}
	
	protected function tree( $selected = '' ) {
		
		$list = Db::name('area')->select();
		$this->tree = Arr2Sibling($list);
		$this->assign('options', TplOptions($this->tree, $selected, 'name','area_id' ));
		
	}
    
}
